RESTful API
Learn about the REST API with the help of some examples.
We'll cover the following
What is a REST API?#
The clients' programs use web APIs to communicate with the web servers. A web API takes the client's requests, interacts with the back-end servers, and responds back to the clients.
Many of today's APIs can be classified as REST APIs. Our purpose is not mere understanding but rather drawing insights into the REST architectural style of developing APIs.
Note: A REST API is a web API that conforms to the commonly used REST architectural style.
Many programming languages and protocols use CRUD operations for manipulating data. For example, in the SQL database, we use insert, select, update, and delete. Similarly, interacting with the REST application often involves CRUD operations because the REST-based applications are built around resources that need to be created, read, updated, and deleted. REST APIs are protocol agnostics; however, the underlying protocol they use widely for communication is HTTP. Therefore, the CRUD operations can be easily mapped to major HTTP methods, as shown in the following table.
CRUD One-to-One Mapping with HTTP Methods
CRUD Operation | HTTP Method | Description |
CREATE |
|
|
READ |
|
|
UPDATE |
|
|
DELETE |
|
|
What makes an API RESTful?#
In the previous lesson, we studied the REST constraints, collectively called a web architectural style. Now, let's revisit those constraints from a different perspective. This time, we’ll see how an API should follow those constraints that make them a REST API.
-
Client-server: In the client-server setup, communication is initiated by the client via HTTP protocol by calling different HTTP methods. Since client and server are considered independent of each other, applications on both sides can evolve independently without affecting each other.
-
Cache: Caching responses on the client side helps to respond to similar requests, which reduces the client’s perceived latency. The cache header in the HTTP response is set if there is a need to keep the response data on the client. Similarly, it can also have the information about the time after which the data is marked invalidated.
-
Uniform interface: This constraint enables different components to exchange data in a standard way. Therefore, there is a need to have a protocol that provides a standard way of communication. Fortunately, HTTP provides us with the standard way of communication in the form of HTTP methods. Every method has some essential components that should be there to send a request. Similarly, the response also has some standard format that a server sends to the client.
For example, in the following HTTP method, we have
name,URI,HTTP version,hostname, anddatasections. These sections are common in everyPOSTrequest.POST /products/form.php HTTP/1.1
Host: www.example.com
item1=value1&item2=value2The HTTP protocol was created from 1989–1991, while the REST architecture style was proposed in 2000. This shows that HTTP was not created for REST, but REST APIs adopted HTTP as a standard protocol. It indicates that REST can be implemented via any protocol conforming to all the constraints of REST, where HTTP is the best choice. This is because HTTP fulfills most of the constraints that the REST architecture styles proposed.
Point to Ponder
Question 2
What does a RESTful API response contain?
In response to a request from the client, the following data should be included in the response in order to conform to the RESTful API paradigm.
- HTTP status code: The response from the server should contain a status code to give a clear picture to the client about the request status.
- Response/message body: The response from the server also contains the message body that includes the resource representation. Based on the information in the request headers, the server chooses an appropriate representation format. Clients may request data in XML or JSON formats, which specify the format of the data’s plain text representation. For example, if we request a specific book title,
Grokking the API Design, the response may contain the following representation of the data:
{
"book": "Grokking the API Design",
"price": 40,
"author": "Educative",
"rating": "5/5"
}
- HTTP headers: The response also contains headers that provide more context about the response, server, encoding technique, data, content type, number of requests made by the client, and so on.
2 of 2
-
Stateless: REST APIs use HTTP requests that are, by default, stateless. Each request is processed independently without a need for prior data or information.
-
Layered system: This constraint allows a user to deploy different services on different servers. For example, deploying APIs on server I, storing authentication information on server II, storing data on server III, and so on. For this purpose, when using an HTTP request, a client doesn’t know whether it is connected with the end server or any intermediate server.
Developers that adhere to this rule can change server systems without affecting the fundamental request-response process.
-
Code-on-demand: This constraint is optional; however, a client can request the server for some scripts. When a client requests a base object to a server via the HTTP protocol, all the script files and other objects are downloaded and rendered on the client side upon a user’s or client’s event. The following example shows an HTML document containing a script from the server.
REST API best practices#
Now that we understand what makes an API RESTful, let's discuss some best practices when developing RESTful APIs.
Exchange of data via JSON: The REST APIs should use JSON format for sending and receiving data. The other formats—like XML and YAML— lack some common procedures for encoding and decoding the data. On the other hand, a wide range of server-side technologies offer built-in methods to parse and manipulate JSON data. For example,
JSON.parse()andJSON.stringify()are used to convert a JSONstringto a JSON object and convert a JSON object to JSONstring, respectively.
REST APIs can support the following file formats:
application/json: JavaScript Object Notation (JSON) is the most flexible and feature-rich format that is used for most of the resources.application/xml: eXtensible Markup Language (XML) is used rarely for some selected resources.application/x-wbe+xml: This is the Decision Server Event internal XML format. It supports importing, exporting, and deploying event projects, hosting events, and event runtime.application/x-www-form-urlencoded: This is sometimes used to send data to the server in a request, mostly to work around URI length limits when querying the REST API. For example, in this encoding, the variables and values are separated using the equal=symbol—for example,VariableOne=ValueOne&VariableTwo=ValueTwo. Moreover, the non-alphanumeric characters are also replaced with a percent sign and two hexadecimal digits,%HH.multipart/form-data: When sending a large amount of data or text containing non-ASCII characters, thex-www-form-urlencodedis inefficient because for each non-alphanumeric character, it will take three bytes instead of one. Therefore,multipart/form-datashould be used to submit forms containing files, non-ASCII characters, and binary data to avoid sending extra bits of data.
Note: Whenever the data is sent in JSON format to the client, the server should set
Content-Typein the HTTP header toapplication/json. This way, the clients look at theContent-Typeheader and correctly interpret JSON data.
Nesting on endpoints: Different endpoints containing the associated information should be interlinked to make them easier to understand. For example, imagine a platform where multiple users can post their articles. A nesting like
https://www.example.com/posts/userseems logical. Similarly, if we need to get comments for a post, we should add/postId/commentsat the end of the/postspath. The resultant endpoint will becomehttps://www.example.com/posts/postId/comments. This is a good practice through which we can avoid mirroring database structure in our endpoints, keeping the data safe from attackers.
Quiz on nesting endpoints.
Assume that we have a website, www.readitnow.com, containing a list of book titles, IDs, and reviews. Our task is to define an endpoint to recommend books to users based on their reviews. What would a suitable endpoint for the reviews be?
https://www.readitnow/books
https://www.readitnow/books/id/reviews
https://www.readitnow/books/id
None of the above
Use nouns instead of verbs in the paths: We should strictly avoid using verbs instead of nouns in the endpoints. The verbs represent methods (the HTTP already has such methods), while the noun represents entities. Using verbs in the endpoints is not useful and makes the endpoints unnecessarily long. For example, instead of the
https://www.example.com/posts/getUserendpoint, which has the verbget, we should usehttps://www.example.com/posts/user.Error management and standard error codes: We should use HTTP status codes regularly when an error occurs to indicate the nature of the error. This helps the API consumers to understand the problem and handle it on their end if needed. Moreover, we should also add an error message with the status code to help users to take some corrective measures.
Filtering and pagination: Sometimes, the database gets incredibly large. Fetching data from such a database becomes time-consuming and reduces performance. Filtering reduces the requested information from the server and thus the end-to-end query latency. For example, the
https://www.example.com/posts?author=fahimendpoint will fetch the posts authored byfahiminstead of listing all the posts. Similarly, there is a need to paginate data to fetch partial results at a time to minimize page loading time and reduce the burden on the client for loading a bulk of data all at once. Filtering and pagination reduce the usage of server resources and increase performance.Adopting standard security practices: Another best practice we should adopt is making our API invulnerable to malicious attacks. In addition, the communication between the client and server should also be private. More importantly, we should also ensure that the server doesn't send unrelated information to unrelated users. This way, we can restrict users to the data intended for them rather than allow them to access other users' data. For this purpose, we can use HTTPS running on top of SSL/TLS. For example,
https://www.example.com/runs on TLS, while thehttp://www.example.com/doesn't use any TLS features.API versioning: We should offer different versions of the API if we make any changes to it that might affect customers. Versioning can be done in line with semantic versions, like the majority of contemporary software—for example, 2.1.6, to denote major version 2, minor version 1, and the sixth patch. This allows us to gradually discontinue old endpoints rather than forcing everyone to migrate to the new API simultaneously. The v1 endpoint may still be useful for individuals who don't want to migrate, while the v2, with its eye-catching additional features, can benefit those who are ready to switch. API versioning can be done by adding
/v1or/v2to the API path—for example,https://www.example.com/v1andhttps://www.example.com/v2.API documentation: Another good practice is to have comprehensive API documentation to help developers and other consumers to understand the API and use it in their applications. A good API document consists of the following:
Detailed and clear explanation of API endpoints and all other functionality with a proper use case
SDK implementation provided in several state-of-the-art programming languages
Clear instructions related to the integration
Clear updates on the API lifecycle
Error messages and proper status codes to convey clear information about the error
Point to Ponder
Question
Why is Hypertext Transfer Protocol (HTTP) an obvious choice for implementing REST APIs?
As we know, REST is an architectural style independent of any protocol. However, to bring it into practice, there needs to be a protocol that should follow REST constraints. Fortunately, HTTP’s logic matches some of the concepts of the REST style; therefore, developers often choose HTTP for creating REST APIs. Let’s list all of the REST constraints that are supported by default by HTTP:
- HTTP operates in a client-server model.
- HTTP includes headers that mark whether an object should be cached or not.
- HTTP includes verbs (methods) that determine the desired action of HTTP requests, providing a uniform communication interface between different entities.
- HTTP uses a stateless operational model.
Advantages of REST APIs#
REST architecture influences how we view, edit, and transfer material online. It’s the preferred choice of many well-known web services. Let's look at the reasons behind this choice in the list below:
Adaptability: The REST APIs are adaptable because they are able to transfer data in a wide variety of formats and handle a wide variety of requests.
Scalability: Regardless of size or capabilities, they are made to communicate with any two pieces of software. A web application's REST API will be able to swiftly handle the growing volume and variety of queries as it expands and adds more services.
Compatibility: REST APIs employ existing web technologies, so they are very simple to create and operate. A REST API just requires the resource's URL to request it.
Summary#
In this lesson, we discussed the features that make a REST API . The REST APIs are protocol agnostics, but since they should use an underlying protocol for their operability, HTTP is a widespread protocol adopted by REST APIs. One of the reasons for the adoption of HTTP for REST API is that this protocol, by default, fulfills many REST architectural constraints—the significant ones are client-server, cacheability, statelessness, and uniform interface. Further, we also discussed some best practices for designing a REST API and the advantages that REST API brings.
Representational State Transfer (REST): Web Architecture Style
GraphQL: A Query Language for APIs